<template>
	<view>
		<uni-nav-bar :fixed="true" left-icon="back" color="#156DAC" @clickLeft="pageback">
			<view class="header-icon-text-panel">
				<text class="title">{{type == 'add'?'添加任务':'任务信息'}}</text>
			</view>
		</uni-nav-bar>
		<view>
			<uni-forms class="right-form left" :value="formData" ref="form" :rules="rules" errShowType="toast">
				<view class="form-content" style="margin: 50upx auto 30upx auto;padding-top: 30upx;">
					<uni-forms-item required label="任务名称" name="taskName">
						<uni-easyinput class="ipt-ctl" type="text" :disabled="disabled" v-model="formData.taskName" maxlength="20" placeholder="请输入任务名称" />
					</uni-forms-item>
					<uni-forms-item required label="项目部" name="projectDepartmentId">
						<lb-picker class="form-ipt" :disabled="disabled" v-model="formData.projectDepartmentId" :list="projectDepartmentOptions" :props="projectPickerProps" @confirm="(e)=>pickerSelectConfim('projectDepartment',e, projectPickerProps)">
							<view class="form-ipt">
								<text v-if="formData.projectDepartmentName" class="lb-picker-text">{{formData.projectDepartmentName}}</text>
								<text v-else class="placeholder">请选择项目部</text>
							</view>
						</lb-picker>
					</uni-forms-item>
					<uni-forms-item required label="发布人" name="publisherId">
						<lb-picker class="form-ipt" :disabled="disabled" v-model="formData.publisherId" :list="options" :props="userPickerProps" @confirm="(e)=>pickerSelectConfim('publisher',e,userPickerProps)">
							<view class="form-ipt">
								<text v-if="formData.publisherName" class="lb-picker-text">{{formData.publisherName}}</text>
								<text v-else class="placeholder">请选择发布人</text>
							</view>
						</lb-picker>
					</uni-forms-item>
					<uni-forms-item required label="责任人" name="responsibleId">
						<lb-picker class="form-ipt" :disabled="disabled" v-model="formData.responsibleId" :list="options2" :props="userPickerProps" @confirm="(e)=>pickerSelectConfim('responsible',e,userPickerProps)">
							<view class="form-ipt">
								<text v-if="formData.responsibleName" class="lb-picker-text">{{formData.responsibleName}}</text>
								<text v-else class="placeholder">请选择责任人</text>
							</view>
						</lb-picker>
					</uni-forms-item>
					<uni-forms-item label="协助人" name="helperId">
						<!-- <lb-picker class="form-ipt" mode="multiSelector" v-model="formData.helperId" :list="options3" :props="userPickerProps" @confirm="(e)=>pickerSelectConfim('helper',e,userPickerProps)">
							 <view class="form-ipt">
								<text v-if="formData.helperName" class="lb-picker-text">{{formData.helperName}}</text>
								<text v-else class="placeholder" @click="multipleShow = true">请选择责任人</text>
							</view> 
						</lb-picker> -->
						<view class="form-ipt" @click="showMulPicker">
							<text v-if="formData.processPersonnelName"  class="lb-picker-text">{{formData.processPersonnelName}}</text>
							<text v-else class="placeholder">请选择协助人</text>
						</view>
						<multiple-select
							v-model="multipleShow"
							:data="options3"
							label-name="realName"
							value-name="id"
							@confirm="mutipleConfirm"
						></multiple-select>
					</uni-forms-item>
					<uni-forms-item required label="任务类型" name="taskType">
						<lb-picker class="form-ipt" :disabled="disabled" v-model="formData.taskType" :list="taskTypes" :props="dictPickerProps" @confirm="(e)=>pickerSelectConfim('taskType',e,dictPickerProps,'dict')">
							<view class="form-ipt">
								<text v-if="formData.taskTypeVal" class="lb-picker-text">{{formData.taskTypeVal}}</text>
								<text v-else class="placeholder">请选择任务类型</text>
							</view>
						</lb-picker>
					</uni-forms-item>
					<uni-forms-item required label="任务内容" name="taskContent">
						<uni-easyinput type="textarea" :disabled="disabled" v-model="formData.taskContent" placeholder="请输入任务内容"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="备注" name="remark">
						<uni-easyinput type="textarea" :disabled="disabled" v-model="formData.remark" placeholder="请输入备注"></uni-easyinput>
					</uni-forms-item>
					<!-- 处理 -->
					<uni-forms-item v-if="type=='apply'" label="任务完成描述" name="remark">
						<uni-easyinput type="textarea"  v-model="formData.statusDescription" placeholder="请输入任务完成描述"></uni-easyinput>
					</uni-forms-item>
					
				</view>
				<!-- 完成情况 -->
				<view v-if="type=='detail' || type=='check'" class="form-content" style="padding: 10upx 30upx;">
					<uni-forms-item label="完成时间">
						<view class="form-ipt">{{taskCompletionSituation.gmtModified?parseTime(taskCompletionSituation.gmtModified) : ''}}</view>
					</uni-forms-item>
					<uni-forms-item label="表单号">
						<view v-if="formData.formNo" class="form-ipt">
							<view v-for="(item,index) in formData.formNo.split(',')" :key="index" @click="gotoDevopsDetail(item)" style="color: #0081FF;">
								{{item}}
							</view>
						</view>
						<view v-else>- -</view>
					</uni-forms-item>
					<uni-forms-item label="完成描述">
						<view class="form-ipt">{{taskCompletionSituation.operationContent||''}}</view>
					</uni-forms-item>
				</view>
				<!-- 审核 -->
				<view v-if="type=='check'" class="form-content" style="padding: 10upx 30upx;">
					<uni-forms-item label="意见说明" name="remark">
						<uni-easyinput type="textarea"  v-model="formData.statusDescription" placeholder="请输入意见说明"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="审核意见">
						<view style="display: flex;flex-direction: row;justify-content: space-around;">
							<view @click="updateForm('e009_04','review')" style="background-color: #156dac;color: #fff;text-align: center;border-radius: 10upx;padding: 5upx;flex: 0 0 120upx;">
								<text>不通过</text>
							</view>
							<view @click="updateForm('e009_03','review')" style="background-color: #156dac;color: #fff;text-align: center;border-radius: 10upx;padding: 5upx;flex: 0 0 120upx;">
								<text>通过</text>
							</view>
						</view>
					</uni-forms-item>
				</view>
				<!-- 审核记录 -->
				<view v-if="type=='detail' && auditResults" class="form-content" style="padding: 10upx 30upx;">
					<uni-forms-item label="审核时间">
						<view class="form-ipt">{{parseTime(auditResults.gmtModified)}}</view>
					</uni-forms-item>
					<uni-forms-item label="结果">
						<view class="form-ipt" :class="formData.taskStatus === 'e009_03'?'green':''">{{formData.taskStatus ? (formData.taskStatus === 'e009_03'?'通过':'不通过'): '- -'}}</view>
					</uni-forms-item>
					<uni-forms-item label="意见">
						<view class="form-ipt">{{auditResults.operationContent||''}}</view>
					</uni-forms-item>
				</view>
				<!-- 关联表单 -->
				<view v-if="type=='apply'" class="form-content" style="padding: 10upx 30upx;">
					<uni-forms-item label="关联表单">
						<view class="form-ipt" @click="showFormMulPicker">
							<text v-if="formData.maintenanceId" class="lb-picker-text">{{formData.maintenanceName}}</text>
							<text v-else class="placeholder">请选择运维表单</text>
						</view>
					</uni-forms-item>
					<multiple-select
						v-model="formMultipleShow"
						:data="maintenances"
						label-name="formNo"
						value-name="id"
						@confirm="formMutipleConfirm"
					></multiple-select>
				</view>
				<button v-if="!disabled" class="form-btn" @click="submitForm">保存</button>
				<button v-if="type == 'apply'" class="form-btn" @click="updateForm('e009_02')">上报</button>
			</uni-forms>
		</view>
	</view>
</template>

<script>
	const saveUrl = '/business/task'
	const detailUrl = '/business/task/maintenance/'
	const getTree = '/base/outlet/listTree'	
	const getTypeUrl = '/base/tOutletEquipment/selectTEquipmentType'
	const reportUrl = '/business/task/report'
	const reviewUrl = '/business/task/review'
	
	const getUserIdUrl = '/base/department/ListProjectDepartment'
	const getPersonUrl = '/system/user/getProjectPersonnel'
	const mainDictUrl = '/business/maintenance/dict'
	const getProcessUrl = '/business/process/list'
	const getDetialByNo = '/business/task/maintenance/'
	
	import multipleSelect from "@/components/momo-multipleSelect/momo-multipleSelect";
	import TimeSelector from '@/components/wing-time-selector/wing-time-selector.vue';
	import LbPicker from '@/components/lb-picker'
	import {getDict} from "@/common/dict.js"
	import {parseTime} from '@/common/util.js'
	export default {
		components:{
			TimeSelector,LbPicker,multipleSelect
		},
		data() {
			return {
				projectPickerProps: {label: 'name',value: 'id'},
				userPickerProps: {label: 'realName',value: 'id'},
				dictPickerProps: {label: 'codeName',value: 'code'},
				typeList: [],
				rules: {
					taskName: {
						rules: [{ required: true, errorMessage: '请选择任务名称'}]
					},
					projectDepartmentId: {
						rules: [{ required: true, errorMessage: '请选择项目部'}]
					},
					publisherId: {
						rules: [{ required: true, errorMessage: '请选择发布人'}]
					},
					responsibleId: {
						rules: [{ required: true, errorMessage: '请选择责任人'}]
					},
					taskType: {
						rules: [{ required: true, errorMessage: '请选择任务类型'}]
					},
					taskContent: {
						rules: [{ required: true, errorMessage: '请输入任务内容'}]
					},
				},
				formData:{
					id: null,
					ids: [],
					num: null,
					taskName: null,
					taskContent: null,
					taskType: null,
					taskTypeVal: '',
					taskStatus: null,
					projectDepartmentId: '',
					projectDepartmentName: '',
					startTime: null,
					remark: null,
					publisherId: '',
					publisherName: '',
					responsibleId: '',
					responsibleName: '',
					helperId: [],
					processPersonnelName: '',
					maintenanceId: [],
					maintenanceName: '',
					statusDescription: null,
					formNo: null
				},
				// 处理
				taskCompletionSituation: {
					operationContent: '‘'
				},
				auditResults: null,
				id: '',
				type: '',
				// dict
				taskTypes: [],
				taskStatus: [],
				multipleShow: false,
				formMultipleShow: false,
				formList: [],
				projectDepartmentOptionsCopy: [],
				projectDepartmentOptions: [],
				optionsCopy: [],
				optionsCopy2: [],
				options: [],
				options2: [],
				options3: [],
				maintenances: [],
				disabled: false
			}
		},
		onLoad(option) {
			this.type = option.type
			this.id = option.id
			this.taskTypes = getDict('e008')
			this.taskTypes.shift()
			this.taskStatus = getDict('e009')
			this.initData()
			// if(this.type === 'detail'){
			// 	this.$api.request(detailUrl+option.id,{
			// 		method: 'get',
			// 	}).then(res=>{
			// 		console.log(res)
			// 	})
			// }
			const eventChannel = this.getOpenerEventChannel()
			eventChannel.on('taskDetail', (res)=> {
			    // console.log("传递： ",res.data)
				if(this.type != 'add'){
					this.disabled = true
					this.formData = res.data
				}
			})
		},
		methods: {
			parseTime,
			pageback() {
				uni.navigateBack({
					delta: 1
				});
			},
			gotoDevopsDetail(no){
				uni.showLoading({
					title:'加载中...',
					mask: true
				})
				this.$api.request(getDetialByNo+no,{
					method: 'get',
				}).then(res=>{
					uni.hideLoading()
					const item = res.data.obj
					const {id} = item
					const overallEvaluation = item.overallEvaluation || 0
					const disposalPersonnelEvaluation = item.disposalPersonnelEvaluation || 0
					const contentDescription = item.contentDescription || ''
					// alert(contentDescription)
					uni.navigateTo({
						url:`/pages/devopsDetail/devopsDetail?type=detail&id=${id}&overallEvaluation=${overallEvaluation}&disposalPersonnelEvaluation=${disposalPersonnelEvaluation}&contentDescription=${contentDescription}`
					})
				}).catch(()=>{
					uni.hideLoading()
				})
			},
			initData() {
				if (this.type !== 'add') {
					// this.conversion()
					this.getTaskProcess()
				  }
				  this.selectBox()
				  // 运维表单选择
				  if (this.type === 'detail' || this.type === 'apply') {
					this.getMaintenanceList()
				  }
			},
			getTaskProcess() {
				this.$api.request(getProcessUrl,{
					method: 'get',
					data: {taskId: this.id}
				}).then(res=>{
					if(res.success){
						res.data.list.forEach(item => {
						  if (item.taskProcessOperationType === 'e010_02') {
							this.taskCompletionSituation = item
						  } else if (item.taskProcessOperationType === 'e010_03') {
							this.auditResults = item
						  }
						})	
					}
				})
			 //  getList({ 'taskId': this.dataForm.id }).then(res => {
				// res.data.list.forEach(item => {
				//   if (item.taskProcessOperationType === 'e010_02') {
				// 	this.taskCompletionSituation = item
				//   } else if (item.taskProcessOperationType === 'e010_03') {
				// 	this.auditResults = item
				//   }
				// })
			 //  })
			},
			mutipleConfirm(e){
				let ids = []
				let names = ''
				if(e.length > 0){
					const name = e.map(item=>{
						ids.push(item.id)
						return item.realName
					})
					names = name.toString()
				}
				this.formData.helperId = ids
				this.formData.processPersonnelName = names
			},
			showMulPicker(){
				if(!this.disabled){
					this.multipleShow = true
				}
			},
			showFormMulPicker(){
				this.formMultipleShow = true
			},
			formMutipleConfirm(e){
				let ids = []
				let names = '请选择运维表单'
				if(e.length > 0){
					const name = e.map(item=>{
						ids.push(item.id)
						return item.formNo
					})
					names = name.toString()
				}
				this.formData.maintenanceId = ids
				this.formData.maintenanceName = names
				
			},
			// 获取运维单
			getMaintenanceList() {
				this.$api.request(mainDictUrl,{
					method: 'get'
				}).then(res=>{
					this.maintenances = res.data.list
					console.log(this.maintenances)
				})
			},
			// 获取下拉框数据
			selectBox() {
				this.$api.request(getUserIdUrl,{
					method: 'get',
				}).then(res=>{
					const projectDepartmentOptions = res.data.projectDepartments
					this.projectDepartmentOptionsCopy = projectDepartmentOptions
					this.projectDepartmentOptions = projectDepartmentOptions
					const role = uni.getStorageSync('USER_ROLE')
					// 如果不是高管 默认选择自己项目部
					const pid = projectDepartmentOptions[0].id
					if (this.type === 'add' && role !== 'e036_02' && role !== 'e036_01') {
					  this.formData.projectDepartmentId = pid
					  if (pid) {
						this.selectBox2(pid)
					  }
					} else {
					  this.selectBox2()
					}
				})
			},
			selectBox2(pid){
				// 如果项目部已选择 查询项目部人员
				const query = {}
				if(pid) query['pid'] = pid
				this.$api.request(getPersonUrl,{
					method: 'get',
					data: query
				}).then(res=>{
					const row = res.data.row
					if(pid){
						this.optionsCopy = row
						// 发布人为主管
						this.optionsCopy2 = []
						this.optionsCopy.forEach(value => {
							if (value.roleType === 'e036_03') {
							  this.optionsCopy2.push(value)
							}
						})
						this.options = this.optionsCopy2
					}else{
						this.optionsCopy = row
						// 发布人为主管
						this.optionsCopy2 = row
						this.options = row
					}
					this.options2 = row
					this.options3 = row
				})
			  // 项目部发生改变，候选人员清空
			  if (this.type === 'add') {
				if (this.formData.publisherId !== '') {
				  this.formData.publisherId = null
				}
				if (this.formData.responsibleId !== '') {
				  this.formData.responsibleId = null
				}
				if (this.formData.helperId !== '') {
				  this.formData.helperId = []
				}
			  }
			},
			getTypeData(outletId) {
				this.$api.request(getTypeUrl,{
					method: 'get',
					data: {
						outletId: outletId
					}
				}).then(res=>{
					if(res.success){
						this.typeList = res.data.list
					}
				}).catch(()=>{
				})
			},
			showPkPicker() {
				this.$refs.tkitree._show()
			},
			pickerSelectConfim(key,e, keyMap,type = null) {
				const {item} = e
				const value = item[keyMap['value']]
				const label = item[keyMap['label']]
				// const {equipmentId, name} = item
				if(!type){
					this.formData[key+ 'Id'] = value
					this.formData[key+'Name'] = label	
				}else if(type == 'dict'){
					this.formData[key] = value
					this.formData[key+'Val'] = label
				}
				
			},
			dateChange(res,type){
				this.formData[type] = res.key
			},
			// 上报/审核
			updateForm(status,type) {
				if(this.formData.taskType === 'e008_02' && status === 'e009_02'){// 需要关联运维表单
					if(!this.formData.maintenanceId || this.formData.maintenanceId === undefined || this.formData.maintenanceId.length <= 0){
						this.$api.toastMsg('请先关联运维表单')
						return
					}
				}
				uni.showLoading({
					title:'保存中',
					mask: true
				})
				let url = reportUrl
				if(type == 'review'){
					url = reviewUrl
				}
				this.formData.taskStatus = status
				this.$api.request(url,{
					method: 'put',
					data: this.formData
				}).then(res=>{
					uni.hideLoading()
					if(res.success){
						this.$api.toastMsg('保存成功','success')
						setTimeout(()=>{
							uni.navigateBack()
						},1000);
					}else{
						this.$api.toastMsg(res.message)
					}
				}).catch((e)=>{
					console.log(e)
					uni.hideLoading()
				})
			},
			submitForm(){
				this.$refs.form.submit().then((res)=>{
					// console.log('表单返回得值：', res)
					const {oldPass,newPass,checkPass} = res
					uni.showLoading({
						title:'保存中',
						mask: true
					})
					this.$api.request(saveUrl,{
						method: 'post',
						data: this.formData
					}).then(res=>{
						uni.hideLoading()
						if(res.success){
							this.$api.toastMsg('保存成功','success')
							setTimeout(()=>{
								uni.navigateBack()
							},1000);
						}
						
					}).catch(()=>{
						uni.hideLoading()
					})
				}).catch(err=>{
					console.log(err)
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.form-ipt{
		line-height: 72upx;
		&.green{
			color: rgb(68, 168, 68);
		}
		.placeholder{
			color: grey;
		}
	}
</style>
